<?php
/**
 * Create by 11li
 * Date 2020/1/9
 * Time 19:19
 *
 */

namespace app\common\service;


use app\admin\model\User;
use app\common\model\Address;
use app\common\model\Commission;
use app\common\model\Order;
use app\common\model\OrderAddress;
use app\common\model\OrderGoods;
use app\common\model\OrderRemind;
use app\common\model\PaymentRecord;
use app\common\model\Promoter;
use app\common\model\PromoterCount;
use app\common\model\Reservation;
use think\Db;
use think\Exception;

class OrderService extends BaseService
{
	/**
	 * 计算价格
	 * @param $userId
	 * @param $data
	 * @return array|bool
	 */
	public function calculation($userId, $data) {
		try {
			$field = 'g.id as goods_id, g.type as goods_type, g.goods_name, g.image, g.price, g.seller_id, g.stock_number, g.commission,
			 s.id as spec_id, s.price as spec_price, s.name as spec_name, s.image as spec_image, s.stock_number as spec_stock,
			 se.name as seller_name';
			//单商品购买
			if($data['from_type'] == 'goods') {
				if(empty($data['goods_id']) || empty($data['number'])) {
					throw new Exception('请选择要购买的商品及数量');
				}
				
				$specId = !empty($data['spec_id']) ? $data['spec_id'] : 0;
				$goods = Db::name('goods')->alias('g')
					->join('goodsSpec s', 's.goods_id = g.id and s.id = '.$specId, 'left')
					->join('seller se', 'g.seller_id = se.id', 'left')
					->where(['g.id' => $data['goods_id'], 'g.status' => StatusService::STATUS_NORMAL])
					->field($data['number'].' as number,'.$field)
					->select();
				
			} else {
				//购物车结算
				if(empty($data['ids'])) {
					throw new Exception('请选择要结算的商品');
				}
				
				$ids = explode('_', $data['ids']);
				$goods = Db::name('cart')->alias('c')
					->join('goods g', 'c.goods_id = g.id', 'left')
					->join('goodsSpec s', 'c.goods_spec_id = s.id', 'left')
					->join('seller se', 'g.seller_id = se.id', 'left')
					->where([
						'c.status' => StatusService::STATUS_NORMAL,
						'g.status' => StatusService::STATUS_NORMAL,
						'c.id' => ['in', $ids],
						'c.user_id' => $userId
					])
					->field('c.number, '. $field)
					->select();
			}
			
			if(!$goods) {
				throw new Exception('结算商品不存在或已下架');
			}
			
			$list = [];
			$amount = 0;
			$number = 0;
			$deposit = 0;
			$orderType = StatusService::ORDER_TYPE_NORMAL;
			
			foreach ($goods as $item) {
				$sellerId = $item['seller_id'];
				$goodsDeposit = 0;
				$activityId = '';
				if($item['goods_type'] == StatusService::GOODS_TYPE_RESERVATION) {
					$activity = ReservationService::getActivityByGoodsId($item['goods_id'], $userId);
					if($activity) {
						if($activity['order_status'] != -1) {
							throw new Exception($activity['order_status'] == 0 ? '存在未支付定金订单': '该商品存在预约中订单');
						}
						$orderType = StatusService::ORDER_TYPE_RESERVATION;
						$goodsDeposit = $activity['deposit'] * $item['number'];
						$deposit += $goodsDeposit;
						$activityId = $activity['id'];
					}
				}
				if(!isset($list[$sellerId])) {
					$list[$sellerId] = [
						'seller_name' => $item['seller_name'],
						'seller_id' => $item['seller_id'],
						'order_type' => $orderType,
						'deposit' => $goodsDeposit,
						'amount' => 0,
						'number' => 0,
						'activity_id' => $activityId,
						'goods_list' => []
					];
				}
				
				$stock = $item['spec_stock'] ? : $item['stock_number'];
				if($stock < $item['number']) {
					throw new Exception($item['goods_name'].'库存不足');
				}
				
				$price = $item['spec_price'] ?? $item['price'];
				$item['price'] = $price;
				$list[$sellerId]['amount'] += $item['number'] * $price;
				$amount += $item['number'] * $price;
				$list[$sellerId]['number'] += $item['number'];
				$number += $item['number'];
				$list[$sellerId]['goods_list'][] = $item;
			}
			
			return [
				'amount' => $amount,
				'number' => $number,
				'order_type' => $orderType,
				'deposit' => $deposit,
				'list' => array_values($list)
			];
			
		}  catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	public function getAddress($userId, $addressId = '')
	{
		$where['a.user_id'] = $userId;
		$where['a.status'] = StatusService::STATUS_NORMAL;
		if($addressId) {
			$where['a.id'] = $addressId;
		} else {
			$where['a.is_default'] = 1;
		}
		
		$row = Db::name('address')->alias('a')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where($where)
			->field('a.id, a.name, a.mobile, a.address, p.name as province_name, c.name as city_name, aa.name as area_name')
			->order(['update_time' => 'desc'])
			->find();
		
		return $row;
	}
	
	/**
	 * 创建订单
	 * @param $data
	 * @param array $res
	 * @return array|bool
	 */
	public function createOrder($data, array $res)
	{
		
		Db::startTrans();
		try{
			if(empty($data['address_id'])) {
				throw new Exception('收货地址不能为空');
			}
			
			$remarkStr = $data['remark'] ??'';
			$remarkArr = explode('&', $remarkStr);
			$remark = [];
			if($remarkArr) {
				foreach ($remarkArr as $item) {
					$arr = explode('=', $item);
					if(!empty($arr[0]) && !empty($arr[1])) {
						$remark[$arr[0]] = $arr[1];
					}
				}
			}
			
			$orderModel = new Order();
			$goodsModel = new OrderGoods();
			$addressModel = new OrderAddress();
			$orderIds = [];
			foreach ($res['list'] as $seller) {
				//添加订单
				$orderId = $orderModel->addOrder($data['user_id'], $seller['seller_id'], $seller['amount'], $seller['amount'], $seller['number'], $data['recommend_user_id'], $remark[$seller['seller_id']] ??'');
				if(!$orderId) {
					throw new Exception('添加订单出错');
				}
				
				//添加订单地址
				$addressRes = $addressModel->addRow($orderId, $data['user_id'], $data['address_id']);
				if(!$addressRes) {
					throw new Exception($addressModel->getError());
				}
				
				//添加商品
				$goodsList = [];
				foreach ($seller['goods_list'] as $goods) {
					$price = $goods['price'] ? : $goods['spec_price'];
					$goodsList[] = [
						'order_id' => $orderId,
						'goods_id' => $goods['goods_id'],
						'spec_id' => $goods['spec_id'],
						'number' => $goods['number'],
						'amount' => $price * $goods['number'],
						'commission' => $goods['commission'] * $goods['number'],
						'rebate_rule' => '',
						'goods_name' => $goods['goods_name'],
						'spec_name' => $goods['spec_name']
					];
				}
				
				$goodsRes = $goodsModel->insertAll($goodsList);
				if(!$goodsRes) {
					throw new Exception('添加购买商品出错');
				}
				
				//减库存
				
				//删除购物车
				
				$orderIds[] = $orderId;
			}
			Db::commit();
			return $orderIds;
		} catch (Exception $e) {
			Db::rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	/**
	 * 创建预约订单
	 * @param $data
	 * @param array $res
	 * @return array|bool
	 */
	public function createReservationOrder($data, array $res)
	{
		
		Db::startTrans();
		try{
			if(empty($data['address_id'])) {
				throw new Exception('收货地址不能为空');
			}
			
			$remarkStr = $data['remark'] ??'';
			$remarkArr = explode('&', $remarkStr);
			$remark = [];
			if($remarkArr) {
				foreach ($remarkArr as $item) {
					$arr = explode('=', $item);
					if(!empty($arr[0]) && !empty($arr[1])) {
						$remark[$arr[0]] = $arr[1];
					}
				}
			}
			
			$orderModel = new Order();
			$goodsModel = new OrderGoods();
			$addressModel = new OrderAddress();
			$orderIds = [];
			foreach ($res['list'] as $seller) {
				
				$recordId = ReservationService::getReservationIdByActivityId($seller['activity_id']);
				
				//添加订单
				$orderId = $orderModel->addOrder($data['user_id'], $seller['seller_id'], $seller['amount'], $seller['amount'], $seller['number'], $data['recommend_user_id'], $remark[$seller['seller_id']] ??'', StatusService::ORDER_TYPE_RESERVATION,StatusService::ORDER_WAIT_PAY, $seller['activity_id'], $recordId, $seller['deposit']);
				if(!$orderId) {
					throw new Exception('添加订单出错');
				}
				
				//添加订单地址
				$addressRes = $addressModel->addRow($orderId, $data['user_id'], $data['address_id']);
				if(!$addressRes) {
					throw new Exception($addressModel->getError());
				}
				
				//添加商品
				$goodsList = [];
				foreach ($seller['goods_list'] as $goods) {
					$price = $goods['price'] ? : $goods['spec_price'];
					$goodsList[] = [
						'order_id' => $orderId,
						'goods_id' => $goods['goods_id'],
						'spec_id' => $goods['spec_id'],
						'number' => $goods['number'],
						'amount' => $price * $goods['number'],
						'commission' => $goods['commission'] * $goods['number'],
						'rebate_rule' => '',
						'goods_name' => $goods['goods_name'],
						'spec_name' => $goods['spec_name']
					];
				}
				
				$goodsRes = $goodsModel->insertAll($goodsList);
				if(!$goodsRes) {
					throw new Exception('添加购买商品出错');
				}
				
				//减库存
				
				//删除购物车
				
				$orderIds[] = $orderId;
			}
			Db::commit();
			return $orderIds;
		} catch (Exception $e) {
			Db::rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	public function getList($userId, $page, $status)
	{
		$where = [
			'o.user_id' => $userId,
			'o.is_delete' => StatusService::STATUS_DISABLED
		];
		
		if(strlen($status) > 0) {
			$where['o.status'] = $status;
			$status == 3 && $where['o.comment_status'] = StatusService::STATUS_DISABLED;
		}
		
		
		$total = Db::name('order')->alias('o')->where($where)->count();
		$list = Db::name('order')->alias('o')
			->join('seller s', 'o.seller_id = s.id', 'left')
			->where($where)
			->field('o.id, o.order_no, o.number, o.amount, from_unixtime(o.create_time) as create_time, o.status, o.shipping_status, o.seller_id, s.name as seller_name, comment_status')
			->page($page)
			->order(['o.update_time' => 'desc'])
			->select();
		if($list) {
			$statusList = StatusService::$orderStatusList;
			foreach ($list as &$item) {
				$item['status_text'] = $statusList[$item['status']] ??'';
				$item['goods_list'] = Db::name('orderGoods')->alias('og')
					->join('goods g', 'og.goods_id = g.id', 'left')
					->where(['og.order_id' => $item['id']])
					->field('g.image, og.goods_id, og.goods_name, og.spec_id, og.spec_name, og.amount as price, og.status, og.number')
					->select();
			}
		}
		
		return [
			'total' => $total,
			'list' => $list
		];
	}
	
	public function payOrder($orderId, $userId)
	{
		$order = Order::get([
			'id' => $orderId,
			'user_id' => $userId,
			'status' => ['in', [StatusService::ORDER_WAIT_PAY, StatusService::ORDER_WAIT_LAST]]
		]);
		if(!$order) {
			$this->error = '没有相关待付款订单';
			return false;
		}
		
		$amount = $order['status'] == StatusService::ORDER_WAIT_PAY ? $order['amount'] : $order['amount'] - $order['pay_amount'];
		$obj = new PaymentService();
		$parmentId = $obj->createRecord([$orderId], $userId, $amount);
		if(!$parmentId) {
			$this->error = $obj->getError();
			return false;
		}
		
		$notify = url('v1/weixinNotify','', false, true);
		$user = User::get($userId);
		$parmentRes = $obj->initPayment($parmentId, $amount, $notify, $user['smallapp_openid']);
		if(!$parmentRes) {
			$this->error = $obj->getError();
			return false;
		}
		
		$parmentRes['cart_number'] = CartService::getCartNumber($userId);
		$parmentRes['amount'] = $amount;
		return $parmentRes;
	}
	
	/**
	 * 支付成功
	 * @param $orderId
	 * @param $amount
	 * @param $transactionId
	 * @param int $payType
	 * @return bool
	 */
	public function paySuccess($orderId, $amount, $transactionId, $payType = StatusService::PAY_TYPE_WEIXIN)
	{
		Db::startTrans();
		try {
			//更改订单状态
			$batchModel = new PaymentRecord();
			$row = $batchModel->find($orderId);
			if($row['status'] != StatusService::PAYMENT_STATUS_WAIT) {
				throw new Exception('非待支付记录');
			}
			
			if($row['amount'] != $amount) {
				throw new Exception('金额不匹配');
			}
			
			$paymentRes = $batchModel->save([
				'transaction_no' => $transactionId,
				'pay_time' => time(),
				'status' => StatusService::PAYMENT_STATUS_SUCCESS],['id' => $orderId]);
			if(!$paymentRes) {
				throw new Exception('更改支付记录状态出错');
			}
			
			$orderModel = new Order();
			$orderIds = explode(',', $row['order_id']);
			

			
			$orderList = $orderModel->where(['id' => ['in', $orderIds]])->select();
			foreach ($orderList as $order) {
				$status = $order['status'];
				if($order['order_type'] == StatusService::ORDER_TYPE_RESERVATION && $status == StatusService::ORDER_WAIT_PAY) {
					$data = [
						'status' => StatusService::ORDER_RESERVATION_ING,
						'pay_time' => time(),
						'deposite_transaction_no' => $transactionId,
						'pay_amount' => $order['deposit_amount'],
						'pay_type' => $payType,
						'deposit_status' => 1,
						'pay_status' => StatusService::ORDER_PAYMENT_STATUS_RESERVATION
					];
				}else if($order['order_type'] == StatusService::ORDER_TYPE_RESERVATION && $status == StatusService::ORDER_WAIT_LAST){
					$data =[
						'status' => StatusService::ORDER_WAIT_LAST_OTHER,
						'pay_time' => time(),
						'pay_amount' => $order['amount'],
						'transaction_no' => $transactionId,
						'pay_type' => $payType,
						'pay_status' => StatusService::ORDER_PAYMENT_STATUS_SUCCESS
					];
				} else {
					$data =[
						'status' => StatusService::ORDER_WAIT_SHIP,
						'pay_time' => time(),
						'pay_amount' => $order['amount'],
						'transaction_no' => $transactionId,
						'pay_type' => $payType,
						'pay_status' => StatusService::ORDER_PAYMENT_STATUS_SUCCESS
					];
				}
				
				$orderRes = $order->save($data, ['id' => $order['id']]);
				if($orderRes === false) {
					throw new Exception('更改订单状态出错');
				}
				if($order['order_type'] == StatusService::ORDER_TYPE_RESERVATION ) {
					if($status == StatusService::ORDER_WAIT_PAY) {
						$reservationRes = ReservationService::addNumber($order['record_id']);
					} else if($status = StatusService::ORDER_WAIT_LAST_OTHER) {
						$reservationRes = ReservationService::addPayNumber($order['record_id']);
					}
				}
				
				//订单成功才执行
				if($order['recommend_user_id'] && $data['status'] == StatusService::ORDER_WAIT_SHIP) {
					//添加商品销量
					$numberRes = (new GoodsService())->changeSaleNumber($order['id']);
					
					//添加推荐人数据
					if($order['recommend_user_id']) {
						$recommendRes = (new PromoterService())->addNumber($order['id']);
					}
					
					//添加订单返利队列
					$rebateRes = $this->addRebateRecord($order['id']);
					if(!$rebateRes) {
						throw new Exception('添加佣金记录出错'.$this->error);
					}
				}
			}
			Db::commit();
			return true;
		} catch (Exception $e) {
			Db::rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	public function addRemindRecord($id, $userId) {
		if(empty($id) || empty($userId)) {
			$this->error = '参数错误';
			return false;
		}
		
		$model = new Order();
		$order = $model->getOrderById($id);
		if(!$order || $order['user_id'] != $userId) {
			$this->error = '订单不存在';
			return false;
		}
		
		if($order['status'] != StatusService::ORDER_WAIT_SHIP) {
			$this->error = '非待发货订单';
			return false;
		}
		
		//添加发货提醒
		$remindModel = new OrderRemind();
		
		
		$res = $remindModel->addRecord($order['id'], $order['seller_id']);
		if(!$res) {
			$this->error = $remindModel->getError();
			return false;
		}
		
		return true;
	}
	
	
	/**
	 * 发货
	 * @param $orderId
	 * @param $type
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function sendShipping($orderId, $type)
	{
		$model = new Order();
		$order = $model->getOrderById($orderId);
		if ($order['status'] != StatusService::ORDER_WAIT_SHIP) {
			$this->error = '非待发货订单';
			return false;
		}
		
		
		//更改订单状态
		if($type == 1) {
			//部分发货
			$data = [
				'shipping_status' => StatusService::ORDER_SHIPPING_SOME,
				'shipping_time' => time()
			];
			
		} else {
			//全部发货
			$data = [
				'status' => StatusService::ORDER_WAIT_SIGN,
				'shipping_status' => StatusService::ORDER_SHIPPING_WAIT_SIGN,
				'shipping_time' => time()
			];
		}
		
		$res = $model->changeOrderData($orderId, $data);
		if(!$res) {
			$this->error = $model->getError();
			return false;
		}
		
		return true;
	}
	
	public function signOrder($id, $userId)
	{
		if(empty($id) || empty($userId)) {
			$this->error = '参数错误';
			return false;
		}
		
		$model = new Order();
		$order = $model->getOrderById($id);
		if(!$order || $order['user_id'] != $userId) {
			$this->error = '订单不存在';
			return false;
		}
		
		if($order['status'] != StatusService::ORDER_WAIT_SIGN) {
			$this->error = '非待签收订单';
			return false;
		}
		
		$model->startTrans();
		try {
			//更改订单状态
			$orderRes = $model->changeOrderData($id, [
				'status' => StatusService::ORDER_DONE,
				'sign_time' => time(),
				'shipping_status' => StatusService::ORDER_SHIPPING_SIGN
			]);
			
			if(!$orderRes) {
				throw new Exception('更改订单状态出错');
			}
			//把佣金状态更改为已到账
			$obj = new FundsService();
			$rebateRes = $obj->sendCommission($id);
			if(!$rebateRes) {
				throw new Exception('发放佣金出错');
			}
			
			$model->commit();
			return true;
		} catch (Exception $e) {
			$model->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	public function deleteOrder($id, $userId)
	{
		if(empty($id) || empty($userId)) {
			$this->error = '参数错误';
			return false;
		}
		
		$model = new Order();
		$order = $model->getOrderById($id);
		if(!$order || $order['user_id'] != $userId) {
			$this->error = '订单不存在';
			return false;
		}
		
		if(!in_array($order['status'], [StatusService::ORDER_DONE, StatusService::ORDER_WAIT_PAY])) {
			$this->error = '该订单不可删除';
			return false;
		}
		
		//更改订单状态
		$orderRes = $model->changeOrderData($id, [
			'is_delete' => StatusService::STATUS_NORMAL,
		]);
		
		if(!$orderRes) {
			$this->error = '删除出错';
			return false;
		}
		
		return true;
	}
	
	public function getOrderDetail($orderId, $userId)
	{
		$order = Db::name('order')->alias('o')
			->join('seller s', 'o.seller_id = s.id', 'left')
			->where([
				'o.id' => $orderId,
				'o.user_id' => $userId
			])
			->field('o.id, o.order_no, o.number, o.amount, from_unixtime(o.create_time) as create_time, o.status, o.shipping_status, o.seller_id, s.name as seller_name, comment_status')
			->find();
		
		if(!$order) {
			$this->error = '订单不存在';
			return false;
		}
		
		$statusList = StatusService::$orderStatusList;
		$order['status_text'] = $statusList[$order['status']] ??'';
		$order['goods_list'] = Db::name('orderGoods')->alias('og')
			->join('goods g', 'og.goods_id = g.id', 'left')
			->where(['og.order_id' => $order['id']])
			->field('g.image, og.goods_id, og.goods_name, og.spec_id, og.spec_name, og.amount as price, og.status, og.number')
			->select();
		
		return $order;
		
	}
	
	/**
	 * 添加待返利记录
	 * @param $orderId
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws Exception
	 */
	public function addRebateRecord($orderId)
	{
		// 订单
		$order = Order::get($orderId);
		
		// 商品
		$orderItems = Db::name('orderGoods')
			->where(['order_id' => $orderId])
			->field('id, goods_id, commission')
			->select();
		
		// 推荐人
		$promoterIds = UserService::getOrderRebateUserId($order['recommend_user_id']);
		$directId = $promoterIds['direct_id'];
		$indirectId = $promoterIds['indirect_id'];
		$topId = $promoterIds['top_id'];
		if(!$directId && !$indirectId && !$topId) {
			return true;
		}
	
		$config = Db::name('rebateSetting')->find();
		if(!$config || ($config['direct_ratio'] == 0 && $config['indirect_ratio'] == 0 && $config['top_ratio'] == 0)) {
			return true;
		}
		$countObj = new PromoterCountService();
		$directDisabled = 0;
		$indirectDisabled = 0;
		$topDisabled = 0;
		foreach ($orderItems as $item) {
			$directCommission = $item['commission']*$config['direct_ratio'];
			$indirectCommission = $item['commission']*$config['indirect_ratio'];
			$topCommission = $item['commission']*$config['top_ratio'];

			if($directCommission > 0 && $directId) {
				$directDisabled += $directCommission;
				$directRes = CommissionService::addRecord($directId, $order['user_id'],
					$orderId, $item['id'], $item['goods_id'], $directCommission);
				if(!$directRes) {
					$this->error = '添加直接推荐人佣金出错';
					return false;
				}
			}
			
			if($indirectCommission > 0 && $indirectId) {
				$indirectDisabled += $indirectCommission;
				$indirectRes = CommissionService::addRecord($indirectId, $order['user_id'],
					$orderId, $item['id'], $item['goods_id'], $indirectCommission);
				if(!$indirectRes) {
					$this->error = '添加间接推荐人佣金出错';
					return false;
				}
			}
			
			if($topCommission > 0 && $topId) {
				$topDisabled += $topCommission;
				$commissionRes = CommissionService::addRecord($topId, $order['user_id'],
					$orderId, $item['id'], $item['goods_id'], $topCommission);
				if(!$commissionRes) {
					$this->error = '添加顶级推荐人佣金出错';
					return false;
				}
			}
		}
		
		//添加推荐人冻结佣金
		if($directDisabled > 0) {
			$promoterRes = (new Promoter())
				->where(['user_id' => $directId])
				->setInc('disabled_commission', $directDisabled);
			if(!$promoterRes) {
				$this->error = '添加直接推荐人冻结佣金出错';
				return false;
			}
		}
		
		
		//添加推荐人冻结佣金
		if($indirectDisabled > 0) {
			$promoterRes = (new Promoter())
				->where(['user_id' => $indirectId])
				->setInc('disabled_commission', $indirectDisabled);
			if(!$promoterRes) {
				$this->error = '添加间接推荐人冻结佣金出错';
				return false;
			}
		}
		
		//添加推荐人冻结佣金
		if($topDisabled > 0) {
			$promoterRes = (new Promoter())
				->where(['user_id' => $topId])
				->setInc('disabled_commission', $topDisabled);
			if(!$promoterRes) {
				$this->error = '添加顶级推荐人冻结佣金出错';
				return false;
			}
		}
		
		
		
		return true;
	}
	
	/**
	 * 获取推荐的订单
	 * @param $userId
	 * @param $page
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getRecommendOrderList($userId, $page)
	{
		$where = [
			'o.recommend_user_id' => $userId,
			'o.pay_status' => StatusService::PAYMENT_STATUS_SUCCESS
		];
		
		$list = Db::name('order')->alias('o')
			->join('seller s', 'o.seller_id = s.id', 'left')
			->where($where)
			->field('o.id, o.order_no, o.number, o.amount, from_unixtime(o.create_time) as create_time, o.status, o.shipping_status, o.seller_id, s.name as seller_name, comment_status')
			->page($page)
			->order(['o.update_time' => 'desc'])
			->select();
		if($list) {
			foreach ($list as &$item) {
				$item['goods_list'] = Db::name('orderGoods')->alias('og')
					->join('goods g', 'og.goods_id = g.id', 'left')
					->where(['og.order_id' => $item['id']])
					->field('g.image, og.goods_id, og.goods_name, og.spec_id, og.spec_name, og.amount as price, og.status, og.number, og.commission')
					->select();
			}
		}
		
		return $list;
	}
	
	/**
	 * @param $orderId
	 * @param $orderType
	 * @param $amount
	 * @param $transaction_id
	 */
	public function refund($orderId, $orderType, $amount, $transaction_id)
	{
		$data = [
			'update_time' => time()
		];
		if($orderType == 'order') {
			$data['pay_status'] = StatusService::ORDER_PAYMENT_STATUS_SUCCESS;
		} else {
			$data['deposit_status'] = StatusService::DEPOSIT_STATUS_REFUND_SUCCESS;
		}
		
		$res = Db::name('order')
			->where(['id' => $orderId])
			->update($data);
	}
}
